package gin_handler

import (
	"strings"

	"github.com/gin-gonic/gin"

	"net/http"

	web_util "app/app_src/framework/util/web"

	file_constants "app/app_src/framework/constant/file"
	web_constants "app/app_src/framework/constant/web"

	error_constants "app/app_src/framework/constant/error"
)

// 处理找不到资源的处理器

func NotFoundHandler(ctx *gin.Context) {
	request := ctx.Request
	header := request.Header
	contentType := header.Get(web_constants.HEADER_CONTENT_TYPE)

	// 根据请求头字段和 URL 后缀决定返回的结果
	if contentType == web_constants.REQUEST_HEADER_CONTENT_TYPE_JSON {
		obj := map[string]any{web_constants.JSON_RESULT_ERROR_CODE: error_constants.UNKNOWN_API}
		ctx.PureJSON(http.StatusNotFound, obj)
	} else {
		url := request.URL
		path := strings.ToLower(url.Path)

		if strings.HasSuffix(path, file_constants.FILE_SUFFIX_HTML) ||
			strings.HasSuffix(path, file_constants.FILE_SUFFIX_HTM) || !strings.Contains(path, ".") {
			web_util.HTML(ctx, http.StatusNotFound, "error/404", nil)
		} else {
			ctx.Status(http.StatusNotFound)
		}
	}
}
